package jnpf.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jnpf.entity.*;
import jnpf.model.zxgl_aIAssistant.ZXGL_AI_UploadKnowledge;
import jnpf.service.*;
import jnpf.util.FileUploadUtil;
import jnpf.util.StringUtil;
import jnpf.utils.AIUtil;
import org.apache.commons.fileupload.FileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ZXGL_UploadKnowledgeTask {

    private static final Logger logger = LoggerFactory.getLogger(ZXGL_UploadKnowledgeTask.class);

    @Autowired
    private AIUtil AIUtil;

    @Autowired
    private ZXGL_XMCFZGBMJSService zxglXmcfzgbmjsService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ZXGL_XiangMuFanKuiService zxglXiangMuFanKuiService;

    @Autowired
    private ZXGL_RenWuFanKuiService zxglRenWuFanKuiService;

    @Autowired
    private ZXGL_XiangMuJieXiangService zxglXiangMuJieXiangService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 每天6点更改当天推送数据推送状态
     */
    //@Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(fixedDelay = 60 * 60 * 1000)   //每隔1小时执行
    @Scheduled(fixedDelay = 1 * 60 * 1000)   //每隔1分钟执行
    public void execute() {
        String token = AIUtil.getAiToken();
        logger.info("token:==================>" + token);
        if (StringUtil.isNotEmpty(token)) {

            logger.info("开始执行上传知识库操作");

            // region 项目分解至部门
            QueryWrapper<ZXGL_XMCFZGBMJSEntity> zXGL_XMCFZGBMJSQueryWrapper = new QueryWrapper<>();
            zXGL_XMCFZGBMJSQueryWrapper.lambda().eq(ZXGL_XMCFZGBMJSEntity::getSfsczsk, 2);
            List<ZXGL_XMCFZGBMJSEntity> zxglXmcfzgbmjsEntityList = zxglXmcfzgbmjsService.list(zXGL_XMCFZGBMJSQueryWrapper);
            if (zxglXmcfzgbmjsEntityList != null && zxglXmcfzgbmjsEntityList.size() > 0) {
                for (ZXGL_XMCFZGBMJSEntity entity : zxglXmcfzgbmjsEntityList) {

                    List<ZXGL_AI_UploadKnowledge> Knowledges = new ArrayList<>();
                    try {
                        if(entity.getLxwj() != null && entity.getLxwj().length() > 4) {
                            Knowledges = objectMapper.readValue(entity.getLxwj(), new TypeReference<List<ZXGL_AI_UploadKnowledge>>() {
                            });
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (Knowledges != null && Knowledges.size() > 0) {

                        for (ZXGL_AI_UploadKnowledge model : Knowledges) {
                            // byte[] bytes = fileUploadProvider.getInputStream("c634602a-e1eb-493c-891e-e20bf56b17ac", model.getFileId(), "annex");
                            byte[] bytes = fileUploadUtil.getInputStream(model.getFileId());
                            logger.info("bytes:{}==================================>" + new String(bytes));
                            model.setBytes(bytes);
                            // File file = ZXGL_Ai_Service.convertByteArrayToFile(bytes,model.getName());
                        }


                        List<ZXGL_XMCFZGBMJS_MingXiEntity> list = zxglXmcfzgbmjsService.GetZXGL_XMCFZGBMJS_MingXiList(entity.getId());
                        if (list != null && list.size() > 0) {
                            boolean upload = true;
                            for (ZXGL_XMCFZGBMJS_MingXiEntity model : list) {
                                Map<String,Object> mapParam = new HashMap<>();
                                mapParam.put("projectId", model.getXmid());
                                mapParam.put("projectName", model.getXmmc());
                                JSONObject jsonResult = AIUtil.uploadKnowledgeBase(token, mapParam, Knowledges);
                                logger.info("jsonResult:==================================>" + jsonResult);
                                if (!jsonResult.getBoolean("success")) {
                                    upload = false;
                                }
                            }
                            if (upload) {
                                entity.setSfsczsk(1);
                                zxglXmcfzgbmjsService.updateById(entity);
                            }

                        }
                    }
                }
            }
            // endregion

            // region 项目反馈
            QueryWrapper<ZXGL_XiangMuFanKuiEntity> zXGL_XiangMuFanKuiQueryWrapper = new QueryWrapper<>();
            zXGL_XiangMuFanKuiQueryWrapper.lambda().eq(ZXGL_XiangMuFanKuiEntity::getSfsczsk, 2);
            List<ZXGL_XiangMuFanKuiEntity> zxglXiangMuFanKuiEntityList = zxglXiangMuFanKuiService.list(zXGL_XiangMuFanKuiQueryWrapper);
            if (zxglXiangMuFanKuiEntityList != null && zxglXiangMuFanKuiEntityList.size() > 0) {
                for (ZXGL_XiangMuFanKuiEntity entity : zxglXiangMuFanKuiEntityList) {


                    List<ZXGL_AI_UploadKnowledge> Knowledges = new ArrayList<>();
                    try {
                        if(entity.getScwj() != null && entity.getScwj().length() > 4) {
                            Knowledges = objectMapper.readValue(entity.getScwj(), new TypeReference<List<ZXGL_AI_UploadKnowledge>>() {
                            });
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (Knowledges != null && Knowledges.size() > 0) {
                        for (ZXGL_AI_UploadKnowledge model : Knowledges) {
                            // byte[] bytes = fileUploadProvider.getInputStream(model.getFileId(), model.getUrl());
                            // byte[] bytes = fileUploadProvider.getInputStream("c634602a-e1eb-493c-891e-e20bf56b17ac", model.getFileId(), "annex");
                            byte[] bytes = fileUploadUtil.getInputStream(model.getFileId());
                            model.setBytes(bytes);
                        }
                        Map<String,Object> mapParam = new HashMap<>();
                        mapParam.put("projectId", entity.getXmid());
                        mapParam.put("projectName", entity.getXmmc());
                        JSONObject jsonResult = AIUtil.uploadKnowledgeBase(token, mapParam, Knowledges);
                        if (jsonResult.getBoolean("success")) {
                            entity.setSfsczsk(1);
                            zxglXiangMuFanKuiService.updateById(entity);
                        }
                    }

                }
            }
            // endregion

            // region 任务反馈
            QueryWrapper<ZXGL_RenWuFanKuiEntity> zXGL_RenWuFanKuiQueryWrapper = new QueryWrapper<>();
            zXGL_RenWuFanKuiQueryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getSfsczsk, 2);
            List<ZXGL_RenWuFanKuiEntity> zxglRenWuFanKuiEntityList = zxglRenWuFanKuiService.list(zXGL_RenWuFanKuiQueryWrapper);
            if (zxglRenWuFanKuiEntityList != null && zxglRenWuFanKuiEntityList.size() > 0) {
                for (ZXGL_RenWuFanKuiEntity entity : zxglRenWuFanKuiEntityList) {

                    List<ZXGL_AI_UploadKnowledge> Knowledges = new ArrayList<>();
                    try {
                        if(entity.getScfj() != null && entity.getScfj().length() > 4) {
                            Knowledges = objectMapper.readValue(entity.getScfj(), new TypeReference<List<ZXGL_AI_UploadKnowledge>>() {
                            });
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (Knowledges != null && Knowledges.size() > 0) {
                        for (ZXGL_AI_UploadKnowledge model : Knowledges) {
                            // byte[] bytes = fileUploadProvider.getInputStream(model.getFileId(), model.getUrl());
                            // byte[] bytes = f fileUploadProvider.getInputStream("c634602a-e1eb-493c-891e-e20bf56b17ac", model.getFileId(), "annex");
                            byte[] bytes = fileUploadUtil.getInputStream(model.getFileId());
                            model.setBytes(bytes);
                        }
                        Map<String,Object> mapParam = new HashMap<>();
                        mapParam.put("projectId", entity.getXmid());
                        mapParam.put("projectName", entity.getSsxm());
                        JSONObject jsonResult = AIUtil.uploadKnowledgeBase(token, mapParam, Knowledges);
                        if (jsonResult.getBoolean("success")) {
                            entity.setSfsczsk(1);
                            zxglRenWuFanKuiService.updateById(entity);
                        }
                    }

                }
            }
            // endregion

            // region 项目结项
            QueryWrapper<ZXGL_XiangMuJieXiangEntity> zXGL_XiangMuJieXiangQueryWrapper = new QueryWrapper<>();
            zXGL_XiangMuJieXiangQueryWrapper.lambda().eq(ZXGL_XiangMuJieXiangEntity::getSfsczsk, 2);
            List<ZXGL_XiangMuJieXiangEntity> zxglXiangMuJieXiangEntityList = zxglXiangMuJieXiangService.list(zXGL_XiangMuJieXiangQueryWrapper);
            if (zxglXiangMuJieXiangEntityList != null && zxglXiangMuJieXiangEntityList.size() > 0) {
                for (ZXGL_XiangMuJieXiangEntity entity : zxglXiangMuJieXiangEntityList) {

                    List<ZXGL_AI_UploadKnowledge> Knowledges = new ArrayList<>();
                    try {
                        if(entity.getJxwj() != null && entity.getJxwj().length() > 4) {
                            Knowledges = objectMapper.readValue(entity.getJxwj(), new TypeReference<List<ZXGL_AI_UploadKnowledge>>() {});
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (Knowledges.size() > 0) {
                        for (ZXGL_AI_UploadKnowledge model : Knowledges) {
                            // byte[] bytes = fileUploadProvider.getInputStream(model.getFileId(), model.getUrl());
                            // byte[] bytes = fileUploadProvider.getInputStream("c634602a-e1eb-493c-891e-e20bf56b17ac", model.getFileId(), "annex");
                            byte[] bytes = fileUploadUtil.getInputStream(model.getFileId());
                            model.setBytes(bytes);
                        }
                        Map<String,Object> mapParam = new HashMap<>();
                        mapParam.put("projectId", entity.getXmid());
                        mapParam.put("projectName", entity.getXmmc());
                        JSONObject jsonResult = AIUtil.uploadKnowledgeBase(token, mapParam, Knowledges);
                        if (jsonResult.getBoolean("success")) {
                            entity.setSfsczsk(1);
                            zxglXiangMuJieXiangService.updateById(entity);
                        }
                    }
                }
            }
            // endregion

            logger.info("结束执行上传知识库操作");
        }


    }
}
